﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.RabbitMQ
{
    public class RabbitMQHelp
    {
        ConnectionFactory _connectionFactory;
        IConnection _connection;

        /// <summary>
        /// 本地连接RabbitMQ
        /// </summary>
        public RabbitMQHelp()
        {
            _connectionFactory = new ConnectionFactory();
            _connection = _connectionFactory.CreateConnection();
        }

        /// <summary>
        /// 远程连接RabbitMQ
        /// </summary>
        /// <param name="ip">服务器IP</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        public RabbitMQHelp(string ip, string userName, string password)
        {
            _connectionFactory = new ConnectionFactory();
            _connectionFactory.HostName = ip;
            _connectionFactory.UserName = userName;
            _connectionFactory.Password = password;
            _connection = _connectionFactory.CreateConnection();
        }

        /// <summary>
        /// 生产消息
        /// </summary>
        /// <param name="queue">队列名称</param>
        /// <param name="message">要发送的消息</param>
        /// <param name="isDurable">是否持久化</param>
        /// <param name="exclusive">是否是唯一的</param>
        public void SendMessage(string queue, string message, bool isDurable = false, bool exclusive = false)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queue, isDurable, exclusive, false, null);
                channel.BasicPublish(string.Empty, queue, null, Encoding.UTF8.GetBytes(message));
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="queue">队列名称</param>
        /// <param name="isDurable">是否持久化</param>
        /// <param name="exclusive">是否是唯一的</param>
        /// <returns></returns>
        public string ReceiveMessage(string queue,bool isDurable = false, bool exclusive = false)
        {
            using (var channel = _connection.CreateModel())
            {
                channel.QueueDeclare(queue, isDurable, exclusive, false, null);
                var consumer = new EventingBasicConsumer(channel);
                BasicGetResult result = channel.BasicGet(queue, true);
                if (result != null)
                {
                    string data = Encoding.UTF8.GetString(result.Body.ToArray());
                    return data;
                }
                return "";
            }
        }
    }
}
